<?php

namespace services\models;

use Yii;

/**
 * This is the model class for table "product_detail".
 *
 * @property string $product_detail_id
 * @property integer $product_id
 * @property string $goods_code
 * @property string $spec_desc
 * @property double $cost_price
 * @property string $stock_price
 * @property string $	barcode
 */
class ProductDetail extends \common\models\ProductDetail
{
    public static function getDb() {
        return \Yii::$app->db;
    }

    public static function getRedis() {
        return \Yii::$app->redis_goods;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id'], 'integer'],
            [['cost_price', 'stock_price'], 'number'],
            [['goods_code'], 'string', 'max' => 60],
            [['spec_desc'], 'string', 'max' => 120],
            [['	barcode'], 'string', 'max' => 100],
        ];
    }

    /**
     * 通过SKU ID获取SKU信息
     * @param int $product_id SKU ID
     * @return array SKU信息
     */
    public static function findByProductId($product_id) {
        $row = self::findByProductIdFromRedis($product_id);
        if(!empty($row) && $row['product_detail_id'] > 0) {
            return $row;
        }

        $var = self::find()->where('product_id=:product_id', [':product_id' => $product_id])->one();
        if(empty($var)) {
            $array = [];
            self::getRedis()->hmset('product_' . $product_id, $array);
            return $array;
        }

        $array = \yii\helpers\ArrayHelper::toArray($var);
        if(!empty($array)) {
            self::getRedis()->hmset('product_' . $product_id, $array);
        }

        return $array;
    }

    /**
     * 通过SKU ID，从数据库获取SKU信息
     * @param int $product_id SKU ID
     * @return array
     */
    public static function findByProductIdFromDb($product_id) {
        $var = self::find()->where('product_id=:product_id', [':product_id' => $product_id])->one();
        if(empty($var)) {
            return [];
        }

        return \yii\helpers\ArrayHelper::toArray($var);
    }

    public static function findByProductIdFromRedis($product_id, $field_array = []) {
        if(empty($field_array)) {
            $field_array = ['product_detail_id', 'product_id', 'goods_code', 'spec_desc', 'cost_price', 'stock_price', 'barcode'];
        }

        return self::getRedis()->hmget('product_' . $product_id, $field_array);
    }
}
